<template>
  <div>
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="changeTab">
      <el-menu-item index="sale" v-if="saleTargetDataSaleCheck">销售</el-menu-item>
      <el-menu-item index="purchase" v-if="saleTargetDataPurchaseCheck">采购</el-menu-item>
      <el-menu-item index="all" v-if="saleTargetDataCheck">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
        <el-form-item label="销售日期：">
          <el-date-picker
            v-model="listQuery.targetDate"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="品类：">
          <el-select
            filterable
            clearable
            v-model="listQuery.goodsName">
            <el-option
              v-for="item in options2"
              :key="item.goodsName"
              :label="item.goodsName"
              :value="item.goodsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.goodsKingId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select size="mini" v-model="listQuery.purchaseUserId" clearable  placeholder="请选择人员" >
            <el-option v-for="item in userOptionList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="销售员：">
          <el-cascader
          size="mini"
          collapse-tags
          :show-all-levels="false"
          v-model="listQuery.userIds"
          placeholder="请选择部门/事业部/人员"
          :options="userList"
          :props="props"></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <div style="font-size:14px;padding:20px 0">汇总目标：<span style="font-weight: bold">{{ saleTargetNum }}</span>吨<span style="padding-left:20px;">实际完成量：<span style="font-weight: bold">{{ saleActualNum }}</span>吨</span><span style="padding-left:20px">完成率：<span style="font-weight: bold">{{ saleFinishedRate }}</span></span></div>
      <el-table
        v-loading="listLoading"
        :span-method="objectSpanMethod"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          prop="targetDate"
          label="销售日期"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.targetDate}}
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="品类"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsSn"
          label="牌号"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsSn}}
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="purchaseUserName"-->
<!--          label="负责采购"-->
<!--          min-width="100"-->
<!--          align="center">-->
<!--          <template slot-scope="scope">-->
<!--            {{scope.row.purchaseUserName}}-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column
          prop="goodsNum"
          label="货源数量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsNum}}
          </template>
        </el-table-column>

        <el-table-column
          v-if="listQuery.tab != 'sale'"
          key="1"
          prop="departmentName"
          label="部门"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.departmentName}}
          </template>
        </el-table-column>
        <el-table-column
          v-if="listQuery.tab != 'sale'"
          prop="departmentSaleTargetNum"
          label="部门目标(吨)"
          key="2"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.departmentSaleTargetNum}}
          </template>
        </el-table-column>
        <el-table-column
          key="3"
          v-if="listQuery.tab != 'sale'"
          prop="departmentSaleActualNum"
          label="部门完成数量(吨)"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.departmentSaleActualNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="销售员"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="saleTargetNum"
          label="个人目标(吨)"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.saleTargetNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="saleActualNum"
          label="个人完成数量(吨)"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.saleActualNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="客户名称"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.customerName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="inquiryCount"
          label="询盘次数"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.inquiryCount}}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderList"
          label="关联订单"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            <span v-for="item in scope.row.orderList" :key="item.orderId" style="padding-left:5px">{{item.orderSn}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="checkContent"
          label="销售员复盘"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.checkContent}}
          </template>
        </el-table-column>
        <el-table-column
          prop="departmentCheckContent"
          label="销售经理复盘"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.departmentCheckContent}}
          </template>
        </el-table-column>
        <el-table-column
          prop="purchaseCheckContent"
          label="采购经理复盘"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.purchaseCheckContent}}
          </template>
        </el-table-column>

        <el-table-column
          v-if="listQuery.tab == 'sale' || listQuery.tab == 'purchase'"
          prop="setting"
          label="操作"
          fixed="right"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="showPop(scope.row,'sale')" v-if="listQuery.tab == 'sale' && !scope.row.departmentCheckTime && scope.row.targetDateTime <= nowdate0">销售经理复盘</el-button>
            <el-button type="text" @click="showPop(scope.row,'purchase')" v-if="listQuery.tab == 'purchase' && !scope.row.purchaseCheckTime && scope.row.targetDateTime <= nowdate0">采购复盘</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--复盘-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
      width="400px">
      <el-form :model="form" size="mini" label-width="110px" ref="form" :rules="rules">
        <el-form-item label="情况说明：" prop="checkContent">
          <el-input v-model="form.checkContent" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>





  </div>
</template>
<script>
import {getOrderUsersList,getGoodsClassList,saleTargetTargetList,orderGoodsList,syncActualSaleNum,targetSummary,targetAnalysis,setActualTarget,setTarget,targetDetail} from '@/api/partner'
import {targetAnalysisList,targetCheck} from '@/api/allInLine/goods.js'
import {saleUserList} from '@/api/data.js'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery={
  "tab" : "", //所有-tab,我的-my,师徒-share,部门-department
  "purchaseUserId" : '',
  "isFinished" : "", //是否已完成(是-1，否-0)
  "targetDate" : '', //目标日期
  userIds:[],
  goodsName:'',
  "pageNum" : 1,
  "pageSize" : 10
};


const defaultForm={
  "goodsKingId" : '', //
  "targetDate" :'',  //
  checkContent:''
}

export default {
  name: "targetReplay",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      loading:false,
      count:0,
      activeName:'first',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      userOptionList:[],
      dialogVisible:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      btnLoading:false,
      goodsList:[],

      rules:{
        checkContent:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      title:'',
      userList:[],
      props:{multiple: true,label:'value',value:'label',emitPath:false},
      options2:[],
      saleTargetNum:0,
      saleActualNum:0,
      saleFinishedRate:0,
      nowdate0:''
    }
  },
  props: {

    nowDate:{
      type: Number,
      default: () => parseInt(Date.parse(new Date())/1000)
    },
    startDate:{
      type: String,
      default: () => ''
    },
    endDate:{
      type: String,
      default: () => ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
    saleTargetDataSaleCheck(){
      if(this.roles.indexOf("saleTargetDataSaleCheck") != -1){
        return true
      }else{
        return false
      }
    },
    saleTargetDataPurchaseCheck(){
      if(this.roles.indexOf("saleTargetDataPurchaseCheck") != -1){
        return true
      }else{
        return false
      }
    },
    saleTargetDataCheck(){
      if(this.roles.indexOf("saleTargetDataCheck") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.listQuery.targetDate = formatDate(new Date(), 'yyyy-MM-dd');
    if(this.saleTargetDataSaleCheck) {
      this.listQuery.tab = 'sale'
    }else if(this.saleTargetDataPurchaseCheck){
      this.listQuery.tab = 'purchase'
    }else if(this.saleTargetDataCheck){
      this.listQuery.tab = 'all'
    }
    this.getList();
    orderGoodsList().then((res)=>{
      this.goodsList = res.list
    })
    this.getUserList();
    this.getUserList2();
    this.remoteMethod3()
    let  date = new Date(); // 获取当前时间
    date.setHours(0, 0, 0, 0); // 将时、分、秒和毫秒设为 0
    this.nowdate0 = parseInt(date.getTime()/1000);
  },
  filters: {



  },
  methods:{
    //获取品类列表
    remoteMethod3() {
      getGoodsClassList().then((res)=>{
        this.options2 = res;
      }).catch(()=>{
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }){
      let rowList1 = ['goodsName','goodsSn','purchaseUserName','targetDate','goodsNum','purchaseCheckContent','setting']
      let rowList2 = ['departmentName','departmentSaleTargetNum','departmentSaleActualNum','departmentCheckContent']
      let rowList3 = ['userName','saleTargetNum','saleActualNum']
      if(rowList1.indexOf(column.property) != -1){
        if (row.isRowSpan1) {
          return {
            rowspan: row.rowNum1,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else if(rowList2.indexOf(column.property) != -1){
        if (row.isRowSpan2) {
          return {
            rowspan: row.rowNum2,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else if(rowList3.indexOf(column.property) != -1){
        if (row.isRowSpan3) {
          return {
            rowspan: row.rowNum3,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else{
        return {
          rowspan: 1,
          colspan: 1
        };
      }

    },

    getUserList2(){
      saleUserList().then((res)=>{
        this.userList = res
      })
    },
    changeTab(key){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
      this.listQuery.tab = key;
      this.listQuery.targetDate = formatDate(new Date(), 'yyyy-MM-dd');
      this.handleSearchList()
    },
    showLog(item){
      this.dialogVisible2 = true;
      orderLogs({orderId:item.orderId}).then((res)=>{
        this.logs = res
      })
    },
    getUserList(){
      getOrderUsersList({departmentId:3,status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },

    showPop(item,type){
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      this.form.goodsKingId = item.goodsKingId;
      this.form.targetDate = item.targetDate;
      this.form.type = type
      if(type == 'sale'){
        this.title = '销售经理复盘'
      }else{
        this.title = '采购复盘'
      }
    },

    handleClose(){
      this.dialogVisible = false;
    },
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = {}
          data.goodsKingId = this.form.goodsKingId;
          data.targetDate = this.form.targetDate;
          if(this.form.type == 'sale'){
            data.departmentCheckContent = this.form.checkContent
          }else{
            data.purchaseCheckContent = this.form.checkContent
          }
          targetCheck(data).then((res)=>{
            this.btnLoading = false;
            this.handleClose();
            this.getList();
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },
    farmtList(responseList){
      let  list = []
      responseList.forEach((e1,i1)=>{
        e1.rowNum1 = 0
        e1.departmentList.forEach((e2,i2)=>{
          e2.rowNum2 = 0
          e2.userList.forEach((e3,i3)=>{
            e3.rowNum3 = e3.customerList.length
            e2.rowNum2 = e2.rowNum2 + e3.customerList.length
            e1.rowNum1 = e1.rowNum1 + e3.customerList.length
          })
        })
      })
      responseList.forEach((e1,i1)=>{
        e1.departmentList.forEach((e2,i2)=>{
          e2.userList.forEach((e3,i3)=>{
            e3.customerList.forEach((e4,i4)=>{
              list.push({
                goodsKingId:e1.goodsKingId,
                goodsName:e1.goodsName,
                goodsSn:e1.goodsSn,
                purchaseUserId:e1.purchaseUserId,
                purchaseUserName:e1.purchaseUserName,
                targetDate:e1.targetDate,
                targetDateTime:e1.targetDateTime,
                goodsNum:e1.goodsNum,
                purchaseCheckContent:e1.purchaseCheckContent,
                purchaseCheckTime:e1.purchaseCheckTime,
                rowNum1:e1.rowNum1,
                departmentName:e2.departmentName,
                departmentSaleTargetNum:e2.departmentSaleTargetNum,
                departmentSaleActualNum:e2.departmentSaleActualNum,
                departmentCheckContent:e2.departmentCheckContent,
                departmentCheckTime:e2.departmentCheckTime,
                rowNum2:e2.rowNum2,
                userId:e3.userId,
                userName:e3.userName,
                saleTargetNum:e3.saleTargetNum,
                saleActualNum:e3.saleActualNum,
                rowNum3:e3.rowNum3,
                customerId:e4.customerId,
                customerName:e4.customerName,
                inquiryCount:e4.inquiryCount,
                customerSaleActualNum:e4.customerSaleActualNum,
                orderList:e4.orderList,
                checkContent:e4.checkContent,
                isRowSpan1:i2==0 && i3==0 && i4 == 0 ? true :false,
                isRowSpan2:i3==0 && i4 == 0 ? true :false,
                isRowSpan3:i4 == 0 ? true :false,
              })
            })
          })
        })
      })
      return list
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let pa = JSON.parse(JSON.stringify(this.listQuery))
      targetAnalysisList(pa).then(response => {
        this.tableData = this.farmtList(response.list);
        this.count = response.count;
        this.listLoading = false;
        this.saleTargetNum = response.saleTargetNum
        this.saleActualNum = response.saleActualNum
        this.saleFinishedRate = response.saleFinishedRate
      }).catch(()=>{
        this.listLoading = false;
      });
    },


  },
}
</script>

<style scoped lang="scss">

</style>
